<template>
  <div>
    <van-nav-bar
      type="primary"
      title="城市列表"
      fixed
      left-arrow
      @click-left="$router.push('/')"
    />
    <van-index-bar class="tt" :index-list="indexList" :sticky="false">
        <!-- 当前城市 -->
      <van-index-anchor index="当前城市" />
      <van-cell :title="currentCity" />
        <!-- <van-index-anchor index="#" />
        <van-cell v-for="item in hotList" :key="item.value" :title="item.label" /> -->
        <!-- 热门城市 -->
        <van-index-anchor index="热" />
        <van-cell @click="changeIndex(item.label, item.value)" v-for="item in hotList" :key="item.value" :title="item.label" />
        <!-- A--Z -->
      <div class="tt" v-for="(item, index) in citylist" :key="index">
        <van-index-anchor :index="item.index" />
        <van-cell @click="changeIndex(item.label, item.value)" v-for="(item,index) in item.list" :key="index" :title="item.label" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { cityList, hotList } from '@/api/house'
import { getCityToken, setCityToken, setCityValueToken } from '@/utils/storage'
export default {
  data () {
    return {
      citylist: [], // 城市列表
      indexList: ['#', '热'], // a-z索引列表
      hotList: []
    }
  },
  // 根据本地token实现点击城市列表首页跳到该城市
  methods: {
    changeIndex (name, val) {
      // console.log(name, val)
      setCityToken(name)
      setCityValueToken(val)
      this.$router.push('/index')
    }
  },
  computed: {
    currentCity () {
      return getCityToken() || '上海'
    }
  },
  async created () {
    const { body } = await cityList()
    const res = await hotList()
    console.log(res)
    this.hotList = res.body
    // console.log(body)
    const obj = {}
    // {A:[{item}]}
    // eslint-disable-next-line array-callback-return
    body.map((item) => {
      const i = item.pinyin[0].toUpperCase()
      // console.log(i)
      if (obj[i]) {
        obj[i].push(item)
      } else {
        obj[i] = [item]
      }
    })
    // console.log(obj)
    for (const k in obj) {
      // console.log(k)
      // console.log(obj[k])
      this.citylist.push({ index: k, list: obj[k] })
    }
    this.citylist
      .sort((a, b) => a.index.localeCompare(b.index))
      .forEach((item) => this.indexList.push(item.index))
  }
}
</script>

<style>
/* .van-nav-bar__title {
  position: relative;
} */
.van-index-bar {
  /* position: fixed; */
  padding-top: 55px;
}
.tt {
  text-align: left;
}
</style>
